package org.zhouhe.modules.upload;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

public class UploadUtils {
	private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd.hh.mm.ss");
	private static final SimpleDateFormat pathFmt = new SimpleDateFormat("yyyyMM");
	/**
	 * @param dir - upload/images/下的文件夹名
	 * @param oldName - 原名称
	 * @return String[] - { 文件名，硬盘上的绝对路径（包含文件名），HTTP相对路径（包含文件名） }
	 */
	public static String[] getImagePathInfo(String dir, String oldName) {
		String dynamicDir = pathFmt.format(new Date());
		String relativePath = "upload/images/"+ dir +"/"+ dynamicDir +"/";
		String newName = sdf.format(new Date()) + oldName.substring(oldName.lastIndexOf("."));
		HttpServletRequest request = ServletActionContext.getRequest();
		String absolutePath = request.getSession().getServletContext().getRealPath("/") +"/"+ relativePath;
		File savePath = new File(absolutePath);
		if(!savePath.exists()){
			savePath.mkdir();
		}
		String[] returnVal = new String[] { newName, absolutePath.concat(newName), relativePath.concat(newName) };
		return returnVal;
	}

	public static void writeFile(File source, String filePath) throws Exception {
		FileInputStream fis = new FileInputStream(source);
		FileOutputStream fos = new FileOutputStream(new File(filePath));
		byte[] b = new byte[102400];// 100K
		int v = -1;
		while ((v = fis.read(b)) > 0) {
			fos.write(b, 0, v);
		}
		fos.flush();
		fos.close();
		fos = null;
		fis.close();
		fis = null;
	}
}
